package cn.foodProject.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;

import cn.foodProject.R;
import cn.foodProject.Utils.SpUtils;
import cn.foodProject.bean.MyOkhttp;
import cn.foodProject.bean.MyGson;
import cn.foodProject.bean.MyUrl;
import cn.foodProject.gsonBean.LoginGsonBean;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    private TextView btnRegister;
    private EditText etTelephone;
    private EditText etPassword;
    private Button btnLogin;
    private final Context context = LoginActivity.this;
    private TextView btnWhereismypassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        btnRegister = (TextView) findViewById(R.id.btn_register);
        etTelephone = (EditText) findViewById(R.id.et_phone);
        etPassword = (EditText) findViewById(R.id.et_password);
        btnWhereismypassword = (TextView) findViewById(R.id.btn_whereismypassword);
        btnLogin = (Button) findViewById(R.id.btn_login);

        btnLogin.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        btnWhereismypassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击登录按钮后
            case R.id.btn_login:

                //获取输入框内容并判断是否为空
                final String telephone = etTelephone.getText().toString();
                final String password = etPassword.getText().toString();
                boolean canLogin = !telephone.isEmpty() && !password.isEmpty();

                //若输入框不为空,则传递数据并调用login()方法
                if (canLogin) {
                    //在子线程中进行同步请求
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            login(telephone, password);
                        }
                    }.start();
                } else {
                    Toast.makeText(context, "请不要留空!", Toast.LENGTH_SHORT).show();
                }
                break;

            //点击注册后跳转至注册页面
            case R.id.btn_register:
                startActivity(new Intent(context, RegisterActivity.class));
                break;

            //点击忘记密码
            case R.id.btn_whereismypassword:
                AlertDialog alert = null;
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                alert = builder
                        .setTitle("系统提示")
                        .setMessage("你又忘记密码了?")
                        .setNegativeButton("爬", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton("爬", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create();
                alert.show();
                break;
        }
    }

    /**
     * 用户登录的方法
     * 同步请求
     * @param telephone 手机号码
     * @param password  密码
     */
    public void login(String telephone, String password) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("telephone", telephone);
            jsonObject.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //拼接url
        URL url = MyUrl.getUrl("/user/login");

        //获取call并将请求加入队列
        try {
            Response response = MyOkhttp.getResponse(url, jsonObject.toString());
            if (response.isSuccessful()) {
                String string = response.body().string();
                //用Gson解析Json数据
                final LoginGsonBean loginGsonBean = (LoginGsonBean) MyGson.fromJson(string, LoginGsonBean.class);

                //若登录成功
                if (loginGsonBean.isSuccess()) {
                    Log.d(TAG, "onResponse: " + loginGsonBean.getMessage());

                    //将Sp清空并将当前登录的用户存入
                    SpUtils.clearAll(context);
                    SpUtils.putBean("user", context, loginGsonBean.getData());

                    //提示登录成功
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "欢迎用户" + loginGsonBean.getData().getName(), Toast.LENGTH_SHORT).show();
                        }
                    });

                    //跳转至点餐页面
                    Intent intent = new Intent(context, FoodActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, loginGsonBean.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } else {
                Log.d(TAG, "onFailure: 请求失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "失败!请检查输入或网络!", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
